package com.itheima.supplier.service;

import com.alibaba.fastjson.JSON;
import com.itheima.delaytask.dto.Task;
import com.itheima.delaytask.enums.TaskTypeEnum;
import com.itheima.delaytask.feign.TaskService;
import com.itheima.recharge.RechargeRequest;
import com.itheima.response.ResponseMessage;
import com.itheima.supplier.inf.SupplierService;
import com.itheima.supplier.inf.SupplierTask;
import com.itheima.thirdparty.StatusCode;
import com.itheima.utils.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;

/**
 * Created by 传智播客*黑马程序员.
 */
@Service
@Slf4j
public class SupplierTaskImpl implements SupplierTask {
    
    @Autowired
    private TaskService taskService;
    
    
    @Override
    public void addRetryTask(RechargeRequest rechargeRequest) {
        Task task = new Task();
        TaskTypeEnum taskTypeEnum = TaskTypeEnum.getTaskType(rechargeRequest.getErrorCode());
        task.setTaskType(taskTypeEnum.getTaskType());
        task.setPriority(taskTypeEnum.getPriority());
        //执行时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,2);
        task.setExecuteTime(calendar.getTimeInMillis());
        
        task.setParameters(ProtostuffUtil.serialize(rechargeRequest));
        
        taskService.push(task);
    }

    @Override
    @Scheduled(fixedRate = 1000)
    public void retryRecharge() {
        retry(TaskTypeEnum.ORDER_REQ_FAILED);
    }
    
    
    @Autowired
    private SupplierService supplierService;
    
    private void retry(TaskTypeEnum taskTypeEnum){
        ResponseMessage responseMessage = taskService.poll(taskTypeEnum.getTaskType(), taskTypeEnum.getPriority());
        if (!responseMessage.isFlag() ||  responseMessage.getCode() == StatusCode.ERROR) {
            return;
        }
        
        if (responseMessage.getData() !=null) {
            String task_json = JSON.toJSONString(responseMessage.getData());
            Task task = JSON.parseObject(task_json, Task.class);
            RechargeRequest rechargeRequest = ProtostuffUtil.deserialize(task.getParameters(), RechargeRequest.class);
            rechargeRequest.setRepeat(rechargeRequest.getRepeat()+1);
            log.info("{}消费重试任务,任务类型:{},任务参数:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),taskTypeEnum.getTaskType(),rechargeRequest);
            supplierService.recharge(rechargeRequest);
        }
    }

    @Override
    @Scheduled(fixedRate = 1000)
    public void rechargeException() {
        retry(TaskTypeEnum.REMOTEERROR);
    }


    @Override
    @Scheduled(fixedRate = 1000)
    public void roundRecharge() {
        retry(TaskTypeEnum.BALANCE_NOT_ENOUGH);
    }
}
